package com.totem.base.mybatis.controller;

import com.baomidou.mybatisplus.extension.service.IService;
import com.totem.base.constants.ErrorCode;
import com.totem.base.exception.BaseException;
import com.totem.base.mybatis.UserIdContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.stream.Collectors;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
public class BaseController<EntityService extends IService<T>, T> {
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpServletResponse response;
    @Autowired
    protected EntityService service;

    protected String toFieldErrorString(BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return bindingResult.getFieldErrors().stream().map(error->
                            String.format("\n%s %s.", error.getField(), error.getDefaultMessage()))
                    .collect(Collectors.joining(""));
        }
        return "";
    }

    protected Long currentCustomerId(){
        Long customerId = UserIdContext.getUserId();
        if(customerId==null){
            throw new BaseException(ErrorCode.UNAUTHORIZED);
        }
        return customerId;
    }
}
